const db = wx.cloud.database()
const _ = db.command
const app = getApp()
import $ from '../../utils/tool'

Page({
  data: {
    activeIndex: '-1',
    friendList: [],
    friendRequest: [],
    showIdInput: false,
    inputId: '',
    myId: ''
  },
  onLoad(event) {
    this.setData({
      myId: app.globalData.userInfo._id
    })
    const obj = { currentTarget: { dataset: { index: String(event.index) } } }
    this.tapFriend(obj)
  },

  tapFriend(e) {
    const { currentTarget: { dataset: { index } } } = e
    const { data: { activeIndex } } = this
    if (activeIndex !== index) {
      this.setData({ activeIndex: index })
      if (index === '0') { this.getFriendList() } //我的好友
      else if (index === '1') { this.getFriendRequest() } //好友请求
      else if (index == '2') {} //添加好友
    }
  },

  // 我的好友
  async getFriendList() {
    const { result: userInfo } = await $.callCloud('model_user_getInfo')
    let friendList = userInfo.friendList
    this.setData({friendList: friendList})
  },

  // 好友请求
  getFriendRequest() {
    db.collection('request').where({
      userId: this.data.myId
    }).watch({
      onChange: snapshot => {
        if(snapshot.docChanges.length) {
          let list = snapshot.docChanges[0].doc.list
          this.setData({friendList: list})
          if (list.length) {
            getApp().globalData.requestUserInfo = list
          }else {
            getApp().globalData.requestUserInfo = []
          }
        }
      },
      onError: err => {
        console.log(err)
      }
    })
    let requestIdList = app.globalData.requestUserInfo
    this.setData({friendRequest: requestIdList})
  },


  // 1. 好友请求；更新请求
  updateRequest(e) {
    console.log('updateRequest', e)
    this.setData({
      friendRequest: []
    }, () => {
      this.setData({
        friendRequest: e.detail
      })
    })
  },
  // 更新好友
  updateFriend(e) {
    console.log('updateFriend', e)
    getApp().globalData.userInfo.friendList = e.detail
    this.setData({
      friendList: []
    }, () => {
      this.setData({
        friendList: e.detail
      })
    })
  },

  // 2. 添加好友
  showSearch() {
    this.setData({showIdInput: !this.data.showIdInput}) // 加一个箭头
  },
  handleAddFriend(e) {
    let inputId = e.detail.value
    let myId = this.data.myId
    if ( inputId ) {
      db.collection('request').where({
        userId: inputId
      }).get().then( res => {
        if(res.data.length) { //更新
          if (res.data[0].list.includes(myId)){
            wx.showToast({
              title: '已申请！',
            })
          }
          else { //有人向他加过好友，但是我没加过
            wx.cloud.callFunction({
              name: 'update_request',
              data: {
                collection: 'message',
                where: {
                  userId: myId
                },
                data: `{list: _.unshift('${myId}')}`
              }
            }).then( res => {
              wx.showToast({
                title: '申请成功（更新）',
              })
            })

          }
        }
        else { //添加(没有人向他加过好友)
          db.collection('request').add({
            data: {
              userId: inputId,
              list: [ myId ]
            }
          }).then(res => {
            wx.showToast({
              title: '申请成功（增加）',
            })
          })
        }
      })
    }
  },
  jumpSetting() {
    wx.showModal({
      title: '是否跳转到设置界面登录？',
      success: res => {
        if(res.confirm) {
          wx.switchTab({
            url: '/pages/setting/setting',
          })
        }
      }
    })
  },
  copyMyId() {
    wx.setClipboardData({
      data: this.data.myId,
      success() {
        wx.showToast({
          title: '复制成功',
          duration: 1000
        })
      }
    })
  },
  onShareAppMessage(res) {
    if (res.from == 'button') {
      console.log(res.target) //来自页面的转发按钮
    }
    return {
      title: '番茄计划',
      path: '/pages/home/home',
      imageUrl: '/images/focusInvite.png',
      desc: '一起学习，一起专注😀😀',
      success(res) {
        console.log('成功', res)
      }
    }
  }
})